const Redis = require('redis');
const log = require('./log4js')('REDIS');

// const client = Redis.createClient(6379, '10.208.60.94', {
//   password: 'qweqwe'
// });
const client = Redis.createClient(6379, '127.0.0.1');
client.on('error', function (error) {
  log.error(error);
});
client.on('connect', function () {
  log.info('redis 链接成功');
});
const getAsync = (key) => {
  log.debug('开始查询', key);
  return new Promise((s, r) => {
    client.get(key, function (err, data) {
      if (err) {
        log.error(`查询${key}错误`, err);
        r(0);
        return;
      }
      log.debug(key, data);
      s(data);
    });
  });
};
global.$redis = {
  get: getAsync,
  set: (key, value, timeout) => {
    log.debug('开始设置', key, value);
    return new Promise((s, r) => {
      if (timeout) {
        log.debug('设置过期时间', timeout);
        client.set(key, value, 'EX', timeout, function (err, data) {
          if (err) {
            log.error(`设置${key}错误`, err);
            r(0);
            return;
          }
          log.debug('设置成功', key, value);
          s(data);
        });
      } else {
        client.set(key, value, function (err, data) {
          if (err) {
            log.error(`设置${key}错误`, err);
            r(0);
            return;
          }
          log.debug('设置成功', key, value);
          s(data);
        });
      }

    });
  },
  del: (key) => {
    client.del(key)
  }
};
